<template>
    <div id="box">
        <div id="header">
            <input type="checkbox" v-model="checkedAll" @click="checkAll">
        </div>
        <ul>
            <li v-for="(item, index) in datas" :key="item.id">
                <input type="checkbox" v-model="item.isChecked">
                <span>{{ item.goodName }}</span>
                <button class="btn" @click="item.count = item.count > 1 ? item.count - 1 : 1">-</button>
                <input type="text" v-model="item.count" class="input">
                <button class="btn" @click="item.count++">+</button>
                <span>{{ item.price }}</span>
                <span>{{ item.count * item.price }}</span>
                <span @click="del(index)">删除</span>
            </li>
        </ul>
        <div id="bottom">
            <span @click="delSelect">删除所选</span>
            <span>{{ countAll }}</span>
            <span>{{ countPriceAll }}</span>
            <span @click="clearAll">清空所有</span>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
let datas = ref([
    { id: 1, isChecked: false, goodName: '红米', count: 1, price: 1700 },
    { id: 2, isChecked: true, goodName: 'iqoo', count: 1, price: 2700 },
])
let checkedAll = ref(false)
// 全选
const checkAll = () => {
    checkedAll.value = !checkedAll.value
    datas.value.forEach(item => {
        item.isChecked = this.checkedAll;
    });
}
// 删除单个商品
const del = (index) => {
    if (confirm('确定删除吗')) {
        datas.value.splice(index, 1)
    }
}
// 删除选中商品
const delSelect = () => {
    datas.value = datas.value.filter(item => !item.isChecked)
}
// 清空所有商品
const clearAll = () => {
    datas.value = []
}
// 监听datas的数据判断是否全选
watch(datas, () => {
    checkedAll.value = datas.value.every(item => item.isChecked);
}, { deep: true })
// 计算被勾选的商品数量
const countAll = computed(() => {
    let newCount = 0
    let data = []
    data = datas.value.filter(item => item.isChecked)
    data.forEach((item) => {
        newCount += item.count
    })
    return newCount
})
// 计算被勾选的商品总价格
const countPriceAll = computed(() => {
    let newPrice = 0
    let data = []
    data = datas.value.filter(item => item.isChecked)
    data.forEach((item) => {
        newPrice += (item.price * item.count)
    })
    return newPrice
})
</script>

<style>
* {
    margin: 0;
    padding: 0;
    list-style-type: none;
}

#box {
    width: 300px;
}

ul li {
    display: flex;
    justify-content: space-between;
}

#bottom {
    display: flex;
    justify-content: space-between;
}

.input {
    width: 20px;
}

.btn {
    width: 20px;
}
</style>